package com.century.sjt.adapter;

import android.app.Activity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AlertDialog;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.bumptech.glide.Glide;
import com.century.sjt.R;
import com.century.sjt.activity.order.MyOrderEnteringMessage;
import com.century.sjt.entity.MyOrder;
import com.century.sjt.util.Constant;
import com.century.sjt.util.TipUtil;

import org.json.JSONObject;
import org.json.JSONTokener;

import java.util.HashMap;
import java.util.List;
import java.util.Map;


public class MerchatOrderAdapter extends BaseAdapter {
    private Context mContext;
    private List<MyOrder> mList;
    private LayoutInflater inflater;
    private RequestQueue mQueue;
    private Handler mHandler;
    private String type;
    private static String returnGoodConfirm = Constant.returnGoodConfirm;//退货（ 0:拒绝  1：同意   2：取消）
    private static String orderRefundConfirm = Constant.orderRefundConfirm;//退款（ 0:申请  1：同意   2：取消）
    public MerchatOrderAdapter(Context mContext, List<MyOrder> mList, RequestQueue mQueue, Handler mHandler, String Type) {
        this.mContext = mContext;
        this.mList = mList;
        this.mQueue = mQueue;
        this.mHandler = mHandler;
        this.type = Type;
        inflater = LayoutInflater.from(mContext);
    }

    @Override
    public int getCount() {
        return mList.size();
    }

    @Override
    public Object getItem(int position) {
        return mList.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(final int position, View convertView, ViewGroup parent) {
        ViewHolder holder = null;
        if (convertView == null) {
            holder = new ViewHolder();
            convertView = inflater.inflate(R.layout.sjt_merchatorder_item,null);
//            holder.tv_order_id= (TextView) convertView.findViewById(R.id.tv_order_id);
            holder.tv_order_time= (TextView) convertView.findViewById(R.id.tv_order_time);
            holder.tv_order_amount = (TextView) convertView.findViewById(R.id.tv_order_amount);
            holder.iv_goods_icon= (ImageView) convertView.findViewById(R.id.iv_goods_icon);
            holder.btn_no = (Button) convertView.findViewById(R.id.btn_order_no);
            holder.btn_ok = (Button) convertView.findViewById(R.id.btn_order_ok);
            holder.tv_order_status = (TextView) convertView.findViewById(R.id.tv_order_status);
            holder.tv_order_name = (TextView) convertView.findViewById(R.id.tv_order_name);
            holder.tv_merchat_currency= (TextView) convertView.findViewById(R.id.tv_merchat_currency);
            convertView.setTag(holder);
        } else {
            holder = (ViewHolder) convertView.getTag();
        }
//        holder.tv_order_id.setText(mList.get(position).getOrderId());
        holder.btn_no.setVisibility(View.GONE);
        holder.btn_ok.setVisibility(View.GONE);
        holder.tv_order_status.setVisibility(View.GONE);
        holder.tv_order_time.setText(mList.get(position).getDate());
        holder.tv_order_amount.setText(mList.get(position).getOrderAmount());
        holder.tv_order_status.setText(mList.get(position).getStatusName());
        holder.tv_order_name.setText(mList.get(position).getNickName());
        holder.tv_merchat_currency.setText(mList.get(position).getOrderCurrency());
        Glide.with(mContext).load(mList.get(position).getImage()).into(holder.iv_goods_icon);
        final String Status = mList.get(position).getStatus();
        switch (type){
            case "1":
                holder.btn_ok.setText(mContext.getResources().getString(R.string.btn_send_out_goods));
                holder.btn_ok.setVisibility(View.VISIBLE);
                holder.btn_ok.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        Intent intent = new Intent();
                        intent.setClass(mContext, MyOrderEnteringMessage.class);
                        intent.putExtra("orderId", mList.get(position).getOrderId());
                        intent.putExtra("type", "inputOrder");
                        mContext.startActivity(intent);

                    }
                });
                break;
            case "2":
                holder.tv_order_status.setVisibility(View.VISIBLE);
                break;
            case "3":
                if ("5".equals(Status)){//退货
                    holder.btn_no.setText(mContext.getResources().getString(R.string.btn_refuse_goods_rejected));
                    holder.btn_ok.setText(mContext.getResources().getString(R.string.btn_agree_goods_rejected));
                }else if("7".equals(Status)){//退款
                    holder.btn_no.setText(mContext.getResources().getString(R.string.btn_refuse_goods_refund));
                    holder.btn_ok.setText(mContext.getResources().getString(R.string.btn_agree_goods_refund));
                }
                holder.btn_ok.setVisibility(View.VISIBLE);
                holder.btn_no.setVisibility(View.VISIBLE);
                holder.btn_no.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        if ("5".equals(Status)){//退货
                            ShowToDo(mContext.getResources().getString(R.string.error_refuse_goods_rejected),returnGoodConfirm,"0",mList.get(position).getOrderId(),position);
                        }else if("7".equals(Status)){//退款
                            ShowToDo(mContext.getResources().getString(R.string.error_refuse_goods_refund),orderRefundConfirm,"0",mList.get(position).getOrderId(),position);
                        }
                    }
                });
                holder.btn_ok.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        if ("5".equals(Status)){//退货
                            ShowToDo(mContext.getResources().getString(R.string.error_agree_goods_rejected),returnGoodConfirm,"1",mList.get(position).getOrderId(),position);
                        }else if("7".equals(Status)){//退款
                            ShowToDo(mContext.getResources().getString(R.string.error_agree_goods_refund),orderRefundConfirm,"1",mList.get(position).getOrderId(),position);
                        }
                    }
                });

                break;
            case "4":
                holder.tv_order_status.setVisibility(View.VISIBLE);
                break;

        };
        return convertView;
    }

    class ViewHolder {
        private TextView tv_order_id;
        private TextView tv_order_time;
        private TextView tv_order_amount;
        private ImageView iv_goods_icon;
        private Button btn_no;
        private Button btn_ok;
        private TextView tv_order_status;
        private TextView tv_order_name;
        private TextView tv_merchat_currency;

    }


    private void onMyOrder(final String mQneneURL,final String operate,final String orderId,final int position){
        TipUtil.openProgressDialog(Constant.APPLICATION_NAME,mContext. getResources().getString(R.string.dl_waiting),mContext);
        StringRequest stringRequest = new StringRequest(Request.Method.POST, mQneneURL, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                try {
                    TipUtil.log("接口返回", response, 1);
                    JSONTokener jsonParser = new JSONTokener(response);
                    JSONObject res = (JSONObject) jsonParser.nextValue();
                    String code = res.getString("code");
                    String message = res.getString("message");
                    if (code.equals("200")) {//成功
                        mList.remove(position);
                    } else {//失败
                        TipUtil.showToast(message, mContext, 1);
                    }
                } catch (Exception ex) {
                    ex.printStackTrace();
                    TipUtil.showToast(mContext.getResources().getString(R.string.error_service), mContext, 1);
                }
                TipUtil.closeProgressDialog();
                Message msg = new Message();
                msg.what = 2;
                mHandler.sendMessage(msg);

            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                TipUtil.showToast(mContext.getResources().getString(R.string.error_network), mContext, 1);
                TipUtil.closeProgressDialog();
                Message msg = new Message();
                msg.what = 2;
                mHandler.sendMessage(msg);
            }
        }) {
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                Map<String, String> map = new HashMap<String, String>();
                SharedPreferences mainSharedPreferences =mContext.getSharedPreferences(Constant.TAG, Activity.MODE_PRIVATE);
                String userId = mainSharedPreferences.getString("userId", "");
                map.put("loginId", userId);
                map.put("orderId", orderId);
                map.put("operate", operate);
                return map;
            }
            @Override
            public Map<String, String> getHeaders() throws AuthFailureError {
                SharedPreferences mainSharedPreferences =mContext. getSharedPreferences(Constant.TAG, Activity.MODE_PRIVATE);
                String cookie = mainSharedPreferences.getString("cookie", "");
                String rememberMeValue = mainSharedPreferences.getString("rememberMe", "");
                HashMap localHashMap = new HashMap();
                String cookieValue = cookie + ";" + rememberMeValue;
                localHashMap.put("Cookie", cookieValue);
                return localHashMap;
            }
        };
        mQueue.add(stringRequest);

    }

    public void ShowToDo(final String message,final String mQneneURL,final String operate,final String orderId,final int position){
        AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
        builder.setMessage(message);
        builder.setCancelable(true);
        builder.setNegativeButton(mContext.getResources().getString(R.string.btn_no), new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });
        builder.setPositiveButton(mContext.getResources().getString(R.string.btn_yes), new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
                onMyOrder(mQneneURL,operate,orderId,position);
            }
        });
        builder.setCancelable(false);
        builder.create().show();
    }
}
